<template>
  <div>
    <p class="choose">选择支付方式</p>
    <ul class="chooseway">
      <li v-for="(item,index) in radios" :key="item.index">
        <div class="radio-box" @click="check(index)">
          <label><img :src="item.img" alt="" width="20">{{item.label}}</label>
          <span class="radio" :class="{'on':item.isChecked}"></span>
          <input :value="item.value" class="input-radio" :checked='item.isChecked'  type="radio"
                 :id="item.index">
        </div>
      </li>
    </ul>
    <p class="offer" @click="goOrderSubmit">确认支付</p>
  </div>
</template>

<script type="text/ecmascript-6">
  import $ from 'jquery'
  import {wxApi} from '../../../test/unit/flyme_weixin'
  import {orderGoPay, orderSubmit} from '../../../test/unit/http'
  import {Toast} from 'we-vue'

  export default {
    name: '',
    props: {
      goodsList: {type: Array},
      resultPrice: '',
      appointment: {},
      peerstaffData: {type: Array},
      delayrisk: {},
      insurantData: {type: Array},
      transfervipcard: {},
      buySource: '',
      accountElesignId: ''
    },
    data() {
      return {
        employeeId: '',
        payType: '',
        payEntranceType: '',
        radios: [
          {
            img: require('../../assets/weixinoffer.png'),
            label: '微信支付',
            value: 'PAY_WX',
            isChecked: false
          },
         /* {
            img: require('../../assets/weixinoffer.png'),
            label: '微信支付Y',
            value: 'PAY_WX',
            isChecked: false
          },*/
          {
            img: require('../../assets/xianxia.png'),
            label: '线下支付（仅限现场支付使用）',
            value: 'PAY_UNDERLINE',
            isChecked: false
          }
        ]
      };
    },
    methods: {
      check(index) {
        // 先取消所有选中项
        this.radios.forEach((item) => {
          item.isChecked = false;
        });
        //再设置当前点击项选中
        this.payType = this.radios[index].value;
        if (this.payType == 'PAY_WX') {
          this.payEntranceType = index + 1;
        }
        // 设置值，以供传递
        this.radios[index].isChecked = true;
      },
      orderGoPay(params) {
        let payType = params.payType;
        orderGoPay(params).then(res => {
          console.log(res);
          if (res.code == 100) {
            if (payType == 'PAY_UNDERLINE') {
              this.$router.push({path: 'downloadoffer', query: {orderId: params.orderId}})
            } else {
              console.info(res.object.url);
              window.location.href = res.object.url;
            }
          }
        })
      },
      orderSubmit(params) {
        console.log(params);
        orderSubmit(params).then(res => {
          console.log(res);
          if (res.code == 100) {
            let order = res.object.order;
            let utils = this.$myUtils;
            let baseUrl = utils.getBaseUrl();
            console.log(baseUrl);
            let payType = order.payType;
            if (payType == 'PAY_WX') {
              baseUrl = baseUrl + "/#/payresult?";
            }
            if (payType == 'PAY_WX_YINLIAN') {
              baseUrl = baseUrl + "/#/payresultgold";
            }
            order['busType'] = 'ORDER';
            order['frontUrl'] = baseUrl;
            this.orderGoPay(order);
          } else {
            Toast.text(res.info)
          }
        })
      },
      uniqueGoodsList() {
        let goodsList = [];
        //对goodsList数组去重
        let obj = {};
        for (let i = 0; i < this.goodsList.length; i++) {
          let goods = this.goodsList[i];
          let goodsId = goods.goodsId;
          if (!obj[goodsId]) {
            goodsList.push(goods);
            obj[goodsId] = goodsId;
          }
        }
        console.log('去重后', goodsList);
        return goodsList;
      },
      checkGoodsList(goodsList) {
        console.log("去重后长度", goodsList.length);
        let msg = {'result': true, 'info': '校验无误'};
        if (goodsList.length <= 0) {
          msg = {'result': false, 'info': '订单信息有误，请重新下单'};
        }
        return msg;
      },
      goOrderSubmit() {
        if (this.$myUtils.isNull(this.payType)) {
          Toast.text('未选择支付方式');
          return;
        }
        let orderDetailInfo = [];
        let params = {};
        let goodsList = this.uniqueGoodsList();
        let checkResult = this.checkGoodsList(goodsList);
        if (!checkResult.result) {
          Toast.text(checkResult.info);
          return;
        }
        for (let key in goodsList) {
          let goods = goodsList[key];
          let orderType = goods.orderType;
          let orderDetail = {
            goodsId: goods.goodsId,
            buyNum: goods.goodsNum,
            unitPrice: goods.unitPrice,
            orderType: orderType
          };
          orderDetailInfo.push(orderDetail);
          //orderDetailInfo信息错误,goodsList同卡种数据出现2条 goodsList是从其他页面如submitOrder 传给支付组件的 [{"goodsId":"27C43C0E7F5D42AD99CBE119FF8D1248","buyNum":1,"unitPrice":180,"orderType":1},{"goodsId":"27C43C0E7F5D42AD99CBE119FF8D1248","buyNum":1,"unitPrice":180,"orderType":1}]
          if (orderType == 2 || orderType == 3) {
            params['peerstaffData'] = JSON.stringify(this.peerstaffData);
            console.log(this.appointment);
            $.extend(params, this.appointment);
          }
          if (orderType == 4) {
            params['insurantData'] = JSON.stringify(this.insurantData);
            $.extend(params, this.delayrisk);
          }
          if (orderType == 5) {
            $.extend(params, this.transfervipcard);
          }
        }
        console.log("订单详情数据 " + JSON.stringify(orderDetailInfo));
        params['payType'] = this.payType;
        params['buySource'] = this.buySource;
        params['orderStatus'] = '1';
        params['totalPrice'] = this.resultPrice;
        params['employeeId'] = this.employeeId;
        params['sourceType'] = 0;
        if (this.payType == 'PAY_WX') {
          params['payEntranceType'] = this.payEntranceType;
        }
        if (!this.$myUtils.isNull(this.accountElesignId)) {
          params['accountElesignId'] = this.accountElesignId;
        }
        params['orderDetailData'] = JSON.stringify(orderDetailInfo);
        if (this.payType == 'PAY_UNDERLINE') {
          params['isCheck'] = '2';
        }
        console.log('params',params);
        this.orderSubmit(params);
      },
    },
    created() {
      wxApi.init();
    },
    components: {}
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less" rel="stylesheet/less">
  .choose {
    color: #999;
    font-size: 15px;
    text-align: left;
    padding: 10px 10px 0;
  }

  .chooseway {
    padding-bottom: 60px;

    li {
      border-bottom: 1px solid #eee;
      padding: 10px 0;
      margin: 10px;
    }

    :last-child {
      border-bottom: none;
    }
  }

  .radio-box {
    position: relative;
    height: 25px;
    line-height: 25px;
    font-size: 15px;
    color: #111;
    text-align: left;
    display: flex;

    label {
      flex: 1;
    }

    img {
      vertical-align: middle;
      margin-right: 10px;
      width: 20px;
    }

    .input-radio {
      display: inline-block;
      position: absolute;
      opacity: 0;
      width: 25px;
      height: 25px;
      cursor: pointer;
      right: 0;
      top: 0;
      outline: none;
      -webkit-appearance: none;
    }
  }

  .radio {
    display: inline-block;
    width: 25px;
    height: 25px;
    vertical-align: middle;
    cursor: pointer;
    background: url(../../assets/radio.png) no-repeat;
    background-size: 100% 100%;

  }

  .on {
    background-image: url(../../assets/radiocheaked.png);
    background-size: 100% 100%;
  }

  .offer {
    position: fixed;
    bottom: 0;
    width: 100%;
    background-image: linear-gradient(to left, #4c92ed, #61beec);
    height: 50px;
    line-height: 50px;
    color: #fff;
    z-index: 999;
  }
</style>
